package com.ptmall.app.ui.activity;

import android.annotation.SuppressLint;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alipay.sdk.app.PayTask;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.bean.AddressBean;
import com.ptmall.app.bean.ConfirmOrderInfoBean;
import com.ptmall.app.bean.PageData;
import com.ptmall.app.bean.ShopCarBean;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.ui.adapter.GoodImgAdapter;
import com.ptmall.app.ui.adapter.GoodimgreAdapter;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.SharedPreferencesHelper;
import com.ptmall.app.view.PullToRefreshLayout;
import com.ptmall.app.view.TitleBarView;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import static com.ptmall.app.MainActivity.MANJIAN;
import static com.ptmall.app.MainActivity.PEISONGFEI;

/**
 * Created by Administrator on 2018/10/26.
 */

public class ConfirmOrderActivity extends BaseMvpActivity implements View.OnClickListener {

    private static String mYear;
    private static String mMonth;
    private static String mDay;
    private static String mWay;
    PopupWindow popupWindow;
    private View popView;

    //


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
//    @SuppressLint("HandlerLeak")
//    private Handler mHandler = new Handler() {
//        @SuppressWarnings("unused")
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case SDK_PAY_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
//                    /**
//                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
//                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//                    String resultStatus = payResult.getResultStatus();
//                    // 判断resultStatus 为9000则代表支付成功
//                    if (TextUtils.equals(resultStatus, "9000")) {
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, "支付成功: " + payResult);
//                    } else {
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, "支付失败: " + payResult);
//                    }
//                    break;
//                }
//                case SDK_AUTH_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
//                    String resultStatus = authResult.getResultStatus();
//
//                    // 判断resultStatus 为“9000”且result_code
//                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
//                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
//                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
//                        // 传入，则支付账户为该授权账户
//                        showMsg( "授权成功: " + authResult);
//                    } else {
//                        // 其他状态值则为授权失败
//                        showMsg( "授权失败: " + authResult);
//                    }
//                    break;
//                }
//                default:
//                    break;
//            }
//        };
//    };

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

        }

        ;
    };
    //

    TextView goodsize, goodprice, address_detil, address_phone, address_name;

    List<ShopCarBean> shopCarBeans;

    TitleBarView titlebar;

    RecyclerView confirmgridview;

    GoodimgreAdapter mGoodImgAdapter;

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();
    String allprice = "";
    String addressId = "";
    StringBuffer carids = new StringBuffer();

    View address_view;
    TextView address_null,select_time;

    Button confirmbtn;

    Intent intent;

    String carid;

    EditText desc;

    RelativeLayout rel_youhuijuan;
    TextView tv_youhuijuan,tv_all_price,psf;

    String couponId,couponName = "0",pei_date,pei_time,quname;
    SharedPreferencesHelper sharedPreferencesHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_confirmorder);
    }

    @Override
    public void initViews() {
        sharedPreferencesHelper = new SharedPreferencesHelper(getContext(), "pt");
        rel_youhuijuan = (RelativeLayout) findViewById(R.id.rel_youhuijuan);
        tv_youhuijuan = (TextView) findViewById(R.id.tv_youhuijuan);
        select_time = (TextView) findViewById(R.id.select_time);
        confirmbtn = (Button) findViewById(R.id.confirmbtn);
        address_null = (TextView) findViewById(R.id.address_null);
        address_view = findViewById(R.id.address_view);
        address_detil = (TextView) findViewById(R.id.address_detil);
        address_name = (TextView) findViewById(R.id.address_name);
        address_phone = (TextView) findViewById(R.id.address_phone);
        goodsize = (TextView) findViewById(R.id.goodsize);
        goodprice = (TextView) findViewById(R.id.goodprice);
        confirmgridview = (RecyclerView) findViewById(R.id.confirmgridview);
        titlebar = (TitleBarView) findViewById(R.id.titlebar);
        desc = (EditText) findViewById(R.id.desc);
        tv_all_price = (TextView) findViewById(R.id.all_price);
        psf = (TextView) findViewById(R.id.psf);
        shopCarBeans = (List<ShopCarBean>) getIntent().getSerializableExtra("list");

    }

    @Override
    public void initEvents() {
        totalPrice();
        mGoodImgAdapter = new GoodimgreAdapter(getActivity());
        mGoodImgAdapter.bind(shopCarBeans);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        confirmgridview.setAdapter(mGoodImgAdapter);
        confirmgridview.setLayoutManager(linearLayoutManager);
        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        confirmbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (addressId.equals("")) {
                    showMsg("请选择地址");
                    return;
                }
//                if(!sharedPreferencesHelper.getSharedPreference("xiaoqu", "").equals(quname)){
//                    showMsg("收货地址不再配送范围内");
//                    return;
//                }
//                if(!address_detil.getText().toString().contains("临沂")){
//                    showMsg("收货地址不再配送范围内");
//                    return;
//                }
                if(TextUtils.isEmpty(pei_date)||TextUtils.isEmpty(pei_time)){
                    showMsg("请选择送达时间");
                    return;
                }
//                pop();
                intent = new Intent(getContext(), PayActivity.class);
                intent.putExtra("addressid", addressId);
                intent.putExtra("orders_total", allprice);
                intent.putExtra("cartIds", carid);
                intent.putExtra("desc", desc.getText().toString());
                intent.putExtra("couponid", couponId);
                intent.putExtra("pei_date", pei_date);
                intent.putExtra("pei_time", pei_time);
                startActivity(intent);
            }
        });
        address_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(getContext(), AddressActivity.class);
                intent.putExtra("select", true);
                startActivityForResult(intent, 1);
            }
        });
        rel_youhuijuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                intent = new Intent(getContext(), CouponActivity.class);
                intent.putExtra("is_select", true);
                intent.putExtra("carids", carid.toString());
                startActivityForResult(intent, 2);
            }
        });
        select_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                final Calendar calendar = Calendar.getInstance();
//                int hour = calendar.get(Calendar.HOUR_OF_DAY);
//                int minute = calendar.get(Calendar.MINUTE);
//                //实例化TimePickerDialog对象
//                final TimePickerDialog timePickerDialog = new TimePickerDialog(ConfirmOrderActivity.this, new TimePickerDialog.OnTimeSetListener() {
//                    //选择完时间后会调用该回调函数
//                    @Override
//                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//
//                        //设置TextView显示最终选择的时间
//                        select_time.setText(hourOfDay+":"+minute);
//                    }
//                }, hour, minute, true);
//                timePickerDialog.show();

                intent = new Intent(getContext(), SelectTimeActivity.class);
                startActivityForResult(intent, 3);
            }
        });
        address_null.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), AddressActivity.class);
                intent.putExtra("select", true);
                startActivityForResult(intent, 1);
            }
        });

        getaddress();
        getData();
    }


    /**
     * 支付宝支付业务示例
     */
    public void payV2(View v) {
        String orderInfo = "";   // 订单信息
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ConfirmOrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void totalPrice() {

        String num = "0";
        allprice = "0";

        for (int i = 0; i < shopCarBeans.size(); i++) {
            if (shopCarBeans.get(i).selected) {
                try {
                    num = new BigDecimal(num).add(new BigDecimal(shopCarBeans.get(i).num)).toPlainString();
                    allprice = new BigDecimal(allprice).add(new BigDecimal(shopCarBeans.get(i).num).multiply(new BigDecimal(shopCarBeans.get(i).sell_price)).setScale(2))
                            .setScale(2).toEngineeringString();

                    if(new BigDecimal(shopCarBeans.get(i).num)
                            .multiply(new BigDecimal(shopCarBeans.get(i).sell_price)).doubleValue()
                            >=new BigDecimal(shopCarBeans.get(i).man).doubleValue()){
                        allprice = new BigDecimal(allprice)
                                .subtract(new BigDecimal(shopCarBeans.get(i).jian)).setScale(2).toPlainString();
                    }


                    carids.append(shopCarBeans.get(i).cartId + ",");
                } catch (Exception e) {

                }
            }
        }

        allprice = new BigDecimal(allprice).subtract(new BigDecimal(couponName)).toPlainString();


        carid = carids.toString().substring(0, carids.length() - 1);
        goodprice.setText("￥"+allprice);

        if(new BigDecimal(MANJIAN).doubleValue()<new BigDecimal(allprice).doubleValue()){
            psf.setText("￥0");
            tv_all_price.setText("￥"+allprice);
        }else {
            allprice = new BigDecimal(PEISONGFEI).add(new BigDecimal(allprice)).setScale(2).toPlainString();
            psf.setText("￥"+ PEISONGFEI);
            tv_all_price.setText("￥"+allprice);
        }


        goodsize.setText("共" + num + "件");
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void getaddress() {
        Map<String, String> map = new HashMap<>();
        apiDataRepository.getAddressList(map, new ApiNetResponse<List<AddressBean>>() {
            @Override
            public void onSuccess(List<AddressBean> datas) {
                if (datas.size() == 0) {
                    address_view.setVisibility(View.GONE);
                    address_null.setVisibility(View.VISIBLE);
                    return;
                }
                address_view.setVisibility(View.VISIBLE);
                address_null.setVisibility(View.GONE);
                addressId = datas.get(0).addressId;
                address_detil.setText(datas.get(0).area+datas.get(0).name+datas.get(0).address);
                address_name.setText(datas.get(0).trueName);
                address_phone.setText(datas.get(0).tel);
                quname = datas.get(0).name;
                for (AddressBean addressBean : datas) {
                    if (addressBean.is_default.equals("2")) {
                        addressId = addressBean.addressId;
                        address_detil.setText(addressBean.area+addressBean.name+addressBean.address);
                        address_name.setText(addressBean.trueName);
                        address_phone.setText(addressBean.tel);
                        quname = addressBean.name;
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 1:
                if(data!=null){
                    address_null.setVisibility(View.GONE);
                    address_view.setVisibility(View.VISIBLE);
                    addressId = data.getStringExtra("id");
                    address_name.setText(data.getStringExtra("name"));
                    address_detil.setText(data.getStringExtra("quname")+data.getStringExtra("address"));
                    address_phone.setText(data.getStringExtra("phone"));
                    quname = data.getStringExtra("quname");
                }

                break;
            case 2:
                if(requestCode == 2&&data!=null){
                    couponId = data.getStringExtra("id");
                    couponName = data.getStringExtra("name");
                    tv_youhuijuan.setText("￥"+couponName);
                    totalPrice();
                }
                break;
            case 3:
                if(requestCode == 3&&data!=null){
                    select_time.setText(data.getStringExtra("pei_date")+" "+data.getStringExtra("pei_time"));
                    pei_date = data.getStringExtra("pei_date");
                    pei_time = data.getStringExtra("pei_time");
                }
                break;
        }
    }

    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.popwindow_pay, null);
                popView.findViewById(R.id.btn1).setOnClickListener(this);
                popView.findViewById(R.id.btn2).setOnClickListener(this);
                popView.findViewById(R.id.btn_cancel).setOnClickListener(this);
            }
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1://pay1
                popupWindow.dismiss();
                break;
            case R.id.btn2://pay2
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;
        }
    }

    private void getData(){
        Map<String,String> map = new HashMap<>();
        map.put("amount",allprice);
        map.put("cartIds",carids.toString());
        apiDataRepository.getConfirmDetil(map, new ApiNetResponse<ConfirmOrderInfoBean>() {
            @Override
            public void onSuccess(ConfirmOrderInfoBean data) {
//                pei_date = time2(1);
//                pei_time = data.song_time1;
//                select_time.setText(time2(1)+data.song_time1);
            }
        });
    }

    public String time2(int i){
        final Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, i);
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
        mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
        mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
        mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if("1".equals(mWay)){
            mWay ="日";
        }else if("2".equals(mWay)){
            mWay ="一";
        }else if("3".equals(mWay)){
            mWay ="二";
        }else if("4".equals(mWay)){
            mWay ="三";
        }else if("5".equals(mWay)){
            mWay ="四";
        }else if("6".equals(mWay)){
            mWay ="五";
        }else if("7".equals(mWay)){
            mWay ="六";
        }
        return mYear+"-"+mMonth + "-" + mDay;
    }
}
